package com.dream.dynamic_datasource.utils;

import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * @description:
 * @author: Luo
 * @create: 2020-06-28 10:20
 */
@Component
public class CommonUtil {
    private static SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat dayTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:SS");

    /**
     * 生成uuid
     * @param
     * @date 2020/6/28 10:22
     */
    public  String generateUUID(){
        return UUID.randomUUID().toString().replaceAll("-","").substring(0,32);
    }
    /**
     * MD5加密
     * @param data
     * @date 2020/6/28 16:07
     */
    public  String MD5(String data)   {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            byte[] mdRes = md.digest(data.getBytes());
            return Base64.getEncoder().encodeToString(mdRes);
        } catch (Exception e) {
            return "";
        }

    }
    /**
     * 获取年月日
     * @date 2020/6/28 16:07
     */
    public String getDay(){
        return dayFormat.format(new Date());
    }
    /**
     * 获取时分秒
     * @date 2020/6/28 16:07
     */
    public String getTime(){
        return timeFormat.format(new Date());
    }
    /**
     * 获取年月日时分秒
     * @date 2020/6/28 16:14
     */
    public String getDayTime(){
        return dayTimeFormat.format(new Date());
    }
    /**
     * Integer null转0
     * @param number
     * @date 2020/7/23 14:17
     */
    public int nullToInt(Integer number){
        int a=0;
        try {
            a=number;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  a;
    }
    /**
     * Integer null转-1
     * @param number
     * @date 2020/7/23 14:17
     */
    public int nullTo_1(Integer number){
        int a=-1;
        try {
            a=number;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  a;
    }

    /**
     * 日期字符串
     *
     * @param date             日期
     * @param simpleDateFormat 简单的日期格式
     * @return {@link String}
     */
    public static String dateToString(Date date, String simpleDateFormat) {
        //HH表示24小时制；
        DateFormat dFormat = new SimpleDateFormat(simpleDateFormat);
        String formatDate = null;
        formatDate = dFormat.format(date);
        return formatDate;
    }
    /**
     * 将年月日转换为时间戳
     * @param day
     * @date 2020/8/6 17:55
     */
    public Long dayToLongTime(String day){
        try {
            Date parse = dayFormat.parse(day);
            return parse.getTime();
        } catch (ParseException e) {
            return 0L;
        }
    }
}
